package jk.fox.registry.register;

import com.alibaba.fastjson.JSON;
import jk.fox.common.exception.RpcRegistryException;
import jk.fox.config.registry.zookeeper.ZookeeperConfiguration;
import jk.fox.engine.RpcNodeDefinition;
import jk.fox.registry.zookeeper.ZookeeperClient;
import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;

/**
 * @author cuichao
 * @Description: ZookeeperRegistry
 * @Date: create in 2020/4/16 21:08
 */
public class ZookeeperRegister implements NodeRegister {

    private static Logger logger = Logger.getLogger(ZookeeperRegister.class);

    private ZookeeperClient zookeeper;
    private ZookeeperConfiguration configuration;


    public ZookeeperRegister(ZookeeperConfiguration config,ZookeeperClient zookeeper){
        this.configuration =  config;
        this.zookeeper = zookeeper;
        logger.debug("ZookeeperRegistry has instance");
    }

    @Override
    public void registry(RpcNodeDefinition definition, String url) throws RpcRegistryException {

        String nodePath = zookeeper.getServiceNodePath(definition.getId());
        String configPath = zookeeper.getServiceConfigPath(definition.getId());
        try {
            //挂载配置节点
            zookeeper.get().create().orSetData().creatingParentsIfNeeded().forPath(configPath, JSON.toJSONString(definition).getBytes());
            logger.debug("ZookeeperRegistry create persistentNode is "+configPath);
        }catch (Exception e){
            throw new RpcRegistryException(String.format("%s register zookeeper is failure", configPath ),e);
        }
        try {
            //挂载节点目录
            String ephemeralNodePath = zookeeper.get().create().creatingParentContainersIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(nodePath + "/" + url, url.getBytes());
            logger.debug("ZookeeperRegistry create ephemeralNodePath is "+ ephemeralNodePath);
        }catch (Exception e){
            throw new RpcRegistryException(String.format("%s register zookeeper is failure", nodePath ),e);
        }
    }

    @Override
    public void unRegistry(RpcNodeDefinition definition, String url)throws RpcRegistryException  {
        String nodePath = zookeeper.getServiceNodePath(definition.getId());
        try {
            zookeeper.get().delete().guaranteed().deletingChildrenIfNeeded().forPath(nodePath);
            logger.info("ZookeeperRegistry remove ephemeralPath is "+nodePath);
        }catch (Exception e){
            throw new RpcRegistryException(String.format("%s unRegistry zookeeper is failure", nodePath ),e);
        }
    }




}
